﻿using SoundEngine3.AudioIO;
using SoundEngine3.DataTypes;
using SoundEngine3.DspPlugins.Meta;
using System.Collections.Generic;

namespace WindowsNativeRenderers
{
    public abstract class CommonWindowsRenderer : BaseAudioDriver
    {
        private SampleRates mPossibeSampleRates;

        private ParameterProperties bufferSizeProperty;
        private ParameterProperties sampleRateProperty;
        private int mMS;
        private int mSR;
        private int mSRIndex = 4;

        public CommonWindowsRenderer(string name) : base(name)
        {
        }

        public override void GetGUIControls(List<ParameterProperties> uiControls)
        {
            mPossibeSampleRates = SampleRates.GetCommonSampleRates();

            // Buffer size.
            bufferSizeProperty = new ParameterPropertiesMapper<object>(null, 0,
                delegate
                {
                    return this.mMS;
                }, delegate (object obj, ParameterProperties sender, int index, double value)
                {
                    mMS = (int)value;
                    sender.Display = mMS.ToString();
                    ReSetupOnOwnThread();
                });
            bufferSizeProperty.MinValue = 10;
            bufferSizeProperty.MaxValue = 600;
            bufferSizeProperty.Label = "Latency";
            bufferSizeProperty.Display = mMS.ToString();
            uiControls.Add(bufferSizeProperty);

            // Sample rate.
            sampleRateProperty = new ParameterPropertiesMapper<object>(null, 0,
                delegate
                {
                    return (int)mSRIndex;
                }, delegate (object obj, ParameterProperties sender, int index, double value)
                {
                    mSRIndex = (int)value;

                    mSR = mPossibeSampleRates[mSRIndex];
                    sender.Display = mSR.ToString();
                    ReSetupOnOwnThread();
                });
            sampleRateProperty.MinValue = 0;
            sampleRateProperty.MaxValue = mPossibeSampleRates.Count - 1;
            sampleRateProperty.Label = "Sample rate";
            sampleRateProperty.Display = mSR.ToString();
            uiControls.Add(sampleRateProperty);
        }

        /// <summary>
        /// Re setup on own thread.
        /// </summary>
        /// <param name="bufferSize"></param>
        /// <param name="sampleRate"></param>
        private void ReSetupOnOwnThread()
        {
            Stop();
            Destroy();
            SetupWasapi(mMS, mSR);
            Start();
        }

        public abstract void Destroy();

        public abstract void SetupWasapi(int latencyMs, int sampleRate);
    }
}
